#include "Game.h"
#include "GameState.h"

// constructor
Game::Game()
{
  
}

void Game::Init(const char* title, int width, int height, 
				int bpp, bool fullscreen)
{
	int flags = 0;
	
	// initialize SDL
	SDL_Init(SDL_INIT_EVERYTHING);
	
	// set the title bar text
	SDL_WM_SetCaption(title, title);
	
	if ( fullscreen ) {
		flags = SDL_FULLSCREEN;
	}
	
	// create the screen surface
	m_pScreen = SDL_SetVideoMode(width, height, bpp, flags);
	
	m_bFullscreen = fullscreen;
	
	m_bRunning = true;
	
	printf("Game Initialised Succesfully\n");
	
}

/* 
Our new functions, ChangeState() takes a pointer to a GameState as a parameter and then pushes that state onto the vector of pointers to GameStates, before that it uses the clean function to remove the old state from the stack.
*/
void Game::ChangeState(GameState* state) 
{
	// cleanup the current state
	if ( !states.empty() ) {
		states.back()->Cleanup();
		states.pop_back();
	}
	
	// store and init the new state
	states.push_back(state);
	states.back()->Init();
}

/*
Whereas ChangeState() pushes a state onto the stack and removes the previous state, PushState() pauses the previous state before pushing a new state onto the stack, this state can then be removed and the previous state resumed. Extrememly useful for pausing.
*/
void Game::PushState(GameState* state)
{
	// pause current state
	if ( !states.empty() ) {
		states.back()->Pause();
	}
	
	// store and init the new state
	states.push_back(state);
	states.back()->Init();
}

/*
Remove and resume previous state.
*/
void Game::PopState()
{
	// cleanup the current state
	if ( !states.empty() ) {
		states.back()->Cleanup();
		states.pop_back();
	}
	
	// resume previous state
	if ( !states.empty() ) {
		states.back()->Resume();
	}
}

/*
These functions have now been changed so that they simply allow the current state to handle things, states.back() refers to the last element on the stack (the current state)
*/
void Game::HandleEvents()
{
	// let the state handle events
	states.back()->HandleEvents(this);
}


void Game::Update()
{
	// let the state update the game
	states.back()->Update(this);
}

void Game::Draw()
{
	// let the state draw the screen
	states.back()->Draw(this);
	//SDL_Flip(m_pScreen);
}

void Game::Clean()
{
	while ( !states.empty() ) {
		states.back()->Cleanup();
		states.pop_back();
	}
	
	// shutdown SDL
	SDL_Quit();
}
